<%
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' 版权所有（C）2018 viviworld
' 本程序为自由软件，在自由软件联盟发布的GNU通用公共许可协议的约束下，你可以对其进行再发布及修改。协议版本为第三版或（随你）更新的版本。
' 我们希望发布的这款程序有用，但不保证，甚至不保证它有经济价值和适合特定用途。详情参见GNU通用公共许可协议。
' 你理当已收到一份GNU通用公共许可协议的副本，如果没有，请查阅<http://www.gnu.org/licenses/>

' QQ: 548841861 （木鱼）
' Email： 365zph@gmail.com
' 项目地址：https://gitee.com/banrenma/RefineCMS
' 协议地址： https://gitee.com/banrenma/RefineCMS/blob/master/LICENSE
' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

%>
<% If Not DIRECT_VISIT Then Response.Write "No direct script access allowed" : Response.End%>
<%
Class cls_Menu
    Public iID, sMenuName, iPid, iMenuType, iIsSinglepage, iDataID, iOrder1, iOrder2, sUsername, dCreatedAt, dUpdatedAt, sExcerpt, sKeywords
    Private iPageSize, iAbsolutePage, iPageCount

    Private Sub Class_Initialize
        ' on error resume next
        iID = 0
        sMenuName = ""
        sExcerpt = ""
        sKeywords = ""
        iPid = 0
        iMenuType = 0
        iIsSinglepage = 0
        iDataID = 0
        iOrder1 = 0
        iOrder2 = 0
        iPageSize = 1000
        iAbsolutePage = 1
    End Sub

    Private Sub class_terminate
    End Sub

    Property Get PageCount()
        PageCount = iPageCount
    End Property

    Property Let PageSize(param_pageSize)
        iPageSize = param_pageSize
    End Property

    Property Get AbsolutePage()
        AbsolutePage = iAbsolutePage
    End Property

    Property Let AbsolutePage(param_absolutePage)
        iAbsolutePage = param_absolutePage
    End Property

    Private Function validateMenuname()
        validateMenuname = False
        If Not rfIsEmpty(sMenuName) And rfStrLen(sMenuName) <= 20 Then
            validateMenuname = True
        End If
    End Function

    Private Function menunameExists
        menunameExists = False
        Dim rs, sql
        sql = "SELECT id FROM `menus` WHERE menu_name='" & rfCleanSingleQuotation(sMenuName) & "'"
        rfStartWatch()
        Set rs = g_conn.Execute(sql)
        rfEndWatchWithDB(sql)
        If Not rs.EOF Then
            If rs(0) <> iID Then
                menunameExists = True
            End If    
        End If
        rs.Close
        Set rs = Nothing
    End Function

    Public Sub init(id)
        Dim rs, sql
        Set rs=Server.CreateObject("ADODB.recordset")
        sql = "SELECT id, menu_name, pid, menu_type, is_singlepage, data_id, order_1, order_2, username, updated_at, created_at, excerpt, keywords FROM `menus` WHERE id=" & rfConvertInt(id)
        rfStartWatch()
        rs.Open sql, g_conn, 1, 1
        rfEndWatchWithDB(sql)
        If Not rs.EOF Then
            iID = id
            sMenuName = rs("menu_name")
            sExcerpt = rs("excerpt")
            sKeywords = rs("keywords")
            iPid = rs("pid")
            iMenuType = rs("menu_type")
            iIsSinglepage = rs("is_singlepage")
            iDataID = rs("data_id")
            iOrder1 = rs("order_1")
            iOrder2 = rs("order_2")
            sUsername = rs("username")
            dUpdatedAt = rs("updated_at")
            dCreatedAt = rs("created_at")
        End If
        rs.Close
        Set rs = Nothing
    End Sub

    Public Function save()
        If Not validateMenuname() Then
            save = T("rf_lang_menu_menuname_validate")
            Exit Function
        End If
        If menunameExists Then
            save = T("rf_lang_menu_menuname_exists")
            Exit Function
        End If
        Dim rs, sql
        Dim flagOld
        Set rs = Server.CreateObject("ADODB.recordset")
        rfStartWatch()
        If iID > 0 Then
            sql = "SELECT * FROM menus WHERE id=" & rfConvertInt(iID)
            rs.Open sql, g_conn, 1, 3
            flagOld = rs("menu_type")
        Else
            sql = "SELECT * FROM menus WHERE 1=2"
            rs.Open sql, g_conn, 1, 3
            rs.AddNew
            rs("created_at") = Now()
            flagOld = 0
        End If
        rfEndWatchWithDB(sql)
        rs("menu_name") = sMenuName
        rs("excerpt") = sExcerpt
        rs("keywords") = sKeywords
        rs("pid") = iPid
        rs("menu_type") = iMenuType
        rs("is_singlepage") = iIsSinglepage
        rs("data_id") = iDataID
        rs("username") = Session("rf_user_username")
        rs("updated_at") = Now()
        rfStartWatch()
        rs.Update
        rfEndWatchWithDB("ADO: table.menus:update-save()")
        If iID <= 0 Then
            If rs("pid") = 0 Then
                rs("order_1") = rs("id")
                rs("order_2") = 0
            Else
                Dim parentMenu
                Set parentMenu = new cls_Menu
                parentMenu.init iPid
                If parentMenu.iID > 0 Then
                    rs("order_1") = parentMenu.iOrder1
                    Set parentMenu = Nothing
                Else
                    save = T("rf_lang_menu_parentmenu_can_not_find")
                    Set parentMenu = Nothing
                    Exit Function
                End If
                rs("order_2") = rs("id")
            End If
        End If
        rs.Update
        save = setTpl(flagOld, iMenuType, rs) '处理文章详情或图片详情的模板
        rs.Close
        Set rs = Nothing
    End Function

    Private Function deleteInfoTpl(id)
        Dim infoTpl, infoTpl_del, fs
        infoTpl = getFilenameOfSource(id)
        infoTpl_del = getFilenameOfDel(id)
        Set fs = Server.CreateObject("Scripting.FileSystemObject")
        If fs.FileExists(Server.MapPath(infoTpl)) Then
                fs.MoveFile Server.MapPath(infoTpl), Server.MapPath(infoTpl_del)
        End If
        Set fs = Nothing
    End Function

    Private Function setTpl(flagOld, iMenuType, rs)
        setTpl = True
        Dim infoTpl, infoTpl_del, commonTpl
        commonTpl = RF_TEMPLATE_FOLDER_FRONTEND & "common.asp"
        infoTpl = getFilenameOfSource(rs("id"))
        infoTpl_del = getFilenameOfDel(rs("id"))
        Dim fs, sourceHtml, tf
        Set fs = Server.CreateObject("Scripting.FileSystemObject")
        If (CInt(flagOld)=0 And CInt(iMenuType)=2) Or (CInt(flagOld)=1 And CInt(iMenuType)=2) Then
            rfStartWatch()
            Set tf = new cls_TextFile
            sourceHtml = tf.ReadFile(commonTpl)
            sourceHtml = rfReplaceRegex(sourceHtml, rfCommonTagPattern, T("rf_lang_tpl_commontag_tips"))
            tf.WriteToFile infoTpl, sourceHtml
            Set tf = Nothing 
            rfEndWatch("生成自定义模板")
        End If
        If CInt(flagOld)=2 And CInt(iMenuType)=1 Then
            If fs.FileExists(Server.MapPath(infoTpl)) Then
                fs.MoveFile Server.MapPath(infoTpl), Server.MapPath(infoTpl_del)
            Else
                   setTpl = T("rf_lang_tpl_file_miss") & infoTpl
            End If
        End If
        Set fs = Nothing
    End Function

    Public Function list(param_PID)
        list = null
        Dim rs, sql
        Set rs=Server.CreateObject("ADODB.recordset")
        sql = "SELECT m.id, m.menu_name, m.pid, m.menu_type, m.is_singlepage, m.data_id, m.order_1, m.order_2, m.username, m.updated_at, m.created_at, "
        sql = sql & " pm.menu_name, m.excerpt, m.keywords "
        sql = sql & "  FROM `menus` m LEFT JOIN menus pm ON m.pid=pm.id"
        If param_PID >= 0 Then
            sql = sql & " WHERE m.pid=" & rfConvertInt(param_PID) 
        End If
        sql = sql & " ORDER BY m.order_1, m.order_2"
        rfStartWatch()
        rs.Open sql, g_conn, 1, 1
        rfEndWatchWithDB(sql)
        If Not rs.EOF Then
            rs.PageSize = iPageSize
            rs.AbsolutePage = fmtPaginationAbsolutePage(iAbsolutePage, rs.PageCount)
            iPageCount = rs.PageCount
            iAbsolutePage = rs.AbsolutePage
            list = rs.GetRows(rs.PageSize)
        End If
        rs.Close
        Set rs = Nothing
    End Function

    Private Function getFilenameOfDel(id)
        Dim infoTpl_del, d, curTime
        d = Now
        curTime = Year(d) & Month(d) & Day(d) & Hour(d) & Minute(d) & Second(d)
        getFilenameOfDel = RF_TEMPLATE_FOLDER_FRONTEND & "menu_" & id & "_deleted_" & curTime & ".asp"
    End Function

    Public Function getFilenameOfSource(id)
        getFilenameOfSource = RF_TEMPLATE_FOLDER_FRONTEND & "menu_" & id & ".asp"
    End Function

    Public Sub del
        g_conn.Execute("DELETE FROM `menus` WHERE id=" & rfConvertInt(iID))
        deleteInfoTpl(rfConvertInt(iID)) '无脑伪删除
    End Sub

    Public Function fmtDataFrom(param_is_singlepage, param_data_id)
        fmtDataFrom = T("rf_lang_unknow")
        If param_is_singlepage = 1 Then
            Dim singlepage
            Set singlepage = New cls_singlepage
            singlepage.init(param_data_id)
            If singlepage.iID > 0 Then
                fmtDataFrom = singlepage.sTitle
            End If
            Set singlepage = Nothing
        Else
            Dim category
            Set category = New cls_Category
            category.init(param_data_id)
            If category.iID > 0 Then
                fmtDataFrom = category.sCatName
            End If
            Set category = Nothing
        End If
    End Function

    Public Sub changeOrder(param_direction)
        init rfConvertInt(iID)
        If iID > 0 Then
            Dim rs, sql, tmp, sql1, sql2, sql3
            If iOrder2 = 0 Then
                sql = "SELECT order_1 FROM `menus` "
                If param_direction = "up" Then
                    sql = sql & " WHERE order_1<" & iOrder1 & " ORDER BY order_1 DESC"
                ElseIf param_direction = "down" Then
                    sql = sql & " WHERE order_1>" & iOrder1 & " ORDER BY order_1 ASC"
                Else
                    Exit Sub
                End If
                rfStartWatch()
                Set rs = g_conn.Execute(sql)
                rfEndWatchWithDB(sql)
                If Not rs.EOF Then
                    tmp = rs(0)
                    sql1 = "UPDATE menus SET order_1=-1 WHERE order_1="&tmp&""
                    sql2 = "UPDATE menus SET order_1="&tmp&" WHERE order_1="&iOrder1
                    sql3 = "UPDATE menus SET order_1="&iOrder1&" WHERE order_1=-1"
                    rfStartWatch()
                    g_conn.Execute sql1
                    rfEndWatchWithDB(sql1)
                    rfStartWatch()
                    g_conn.Execute sql2
                    rfEndWatchWithDB(sql2)
                    rfStartWatch()
                    g_conn.Execute sql3
                    rfEndWatchWithDB(sql3)
                End If
            Else
                sql = "SELECT id, order_2 FROM `menus` WHERE pid<>0 AND order_1="&iOrder1
                If param_direction = "up" Then
                    sql = sql & " AND order_2<" & iOrder2 & " ORDER BY order_2 DESC"
                ElseIf param_direction = "down" Then
                    sql = sql & " AND order_2>" & iOrder2 & " ORDER BY order_2 ASC"
                Else
                    Exit Sub
                End If
                Set rs = g_conn.Execute(sql)
                If Not rs.EOF Then
                    sql1 = "UPDATE menus SET order_2="&iOrder2&" WHERE id="&rs("id")
                    sql2 = "UPDATE menus SET order_2="&rs("order_2")&" WHERE id="&iID
                    rfStartWatch()
                    g_conn.Execute sql1
                    rfEndWatchWithDB(sql1)
                    rfStartWatch()
                    g_conn.Execute sql2
                    rfEndWatchWithDB(sql2)
                End If
            End If
           
            Set rs = Nothing
        End If
    End Sub


End Class

%>